package handler

import (
	"github.com/gin-gonic/gin"
	"go-devops/common"
	"go-devops/domain/dto"
	"go-devops/domain/model"
	"go-devops/domain/vo"
	"log"
)

func GetSecretList(c *gin.Context) {
	secretType := c.Query("type")
	list, err := model.QuerySecretList(secretType)
	if err != nil {
		common.BizError(c, "查询密钥失败")
		return
	}

	resultList := make([]*vo.SecretVO, 0)
	for _, secret := range list {
		secretVO := &vo.SecretVO{
			Name:       secret.Name,
			SecretType: secret.SecretType,
		}
		resultList = append(resultList, secretVO)
	}
	log.Printf("GetSecretList resultList:%s\n", common.JsonString(resultList))
	common.OKData(c, resultList)
}

func AddSecret(c *gin.Context) {
	var addSecret dto.AddSecretDTO
	if err := c.ShouldBindJSON(&addSecret); err != nil {
		common.BizError(c, err.Error())
		return
	}

	count, err := model.QuerySecretCount(&addSecret)
	if err != nil {
		common.BizError(c, "添加密钥失败")
		return
	}

	if count > 0 {
		common.BizError(c, "密钥配置已存在，请勿重复添加")
		return
	}

	key := common.Config.Node.Secret

	encryptSecretKey, err := common.AesEncrypt(key, addSecret.SecretKey)
	if err != nil {
		common.BizError(c, "密钥加密失败")
		return
	}

	encryptSecretValue, err := common.AesEncrypt(key, addSecret.SecretValue)
	if err != nil {
		common.BizError(c, "密钥加密失败")
		return
	}

	secret := &model.Secret{
		SecretType:  addSecret.SecretType,
		Name:        addSecret.Name,
		SecretKey:   encryptSecretKey,
		SecretValue: encryptSecretValue,
		CreateTime:  common.NowStr(),
	}

	err = model.AddSecret(secret)
	if err != nil {
		common.BizError(c, "添加密钥失败")
		return
	}
	common.OK(c)
}

func DeleteSecret(c *gin.Context) {
	secretType := c.Query("type")
	name := c.Query("name")

	if len(secretType) <= 0 || len(name) <= 0 {
		common.BizError(c, "字段不能为空")
		return
	}

	if err := model.DeleteSecret(secretType, name); err != nil {
		common.BizError(c, "删除失败")
		return
	}
	common.OK(c)
}
